<template>
	<!-- 三级联动组件 -->
	<u-popup v-model="value" mode="bottom" :popup="false" :mask="true" :closeable="true" :safe-area-inset-bottom="true"
	 close-icon-color="rgb(118, 92, 254)" :z-index="uZIndex" :maskCloseAble="maskCloseAble" @close="close" border-radius="20" >
		<u-tabs v-if="value" :list="genTabsList" active-color="rgb(118, 92, 254)" :is-scroll="true" :current="tabsIndex" @change="tabsChange" ref="tabs"></u-tabs>
    <!-- <view class="send" @click="close">确认</view> -->
		<view class="area-box">
			<view class="u-flex" :class="{ 'change':isChange }">
				<view class="area-item">
					<view class="u-padding-10 u-bg-gray" style="height: 100%;">
						<scroll-view :scroll-y="true" style="height: 100%">
							<!-- <u-cell-group>
								<u-cell-item v-for="(item,index) in provinces" :title="item.label" :arrow="false" :index="index" :key="index"
								 @click="provinceChange">
									<u-icon v-if="isChooseP&&province===index" 
									slot="right-icon" size="34" color="rgb(118, 92, 254)" name="checkbox-mark"></u-icon>
								</u-cell-item>
							</u-cell-group> -->
							<view v-for="(item,index) in provinces" :key="index"
							 @click="provinceChange(index)" class="u-flex u-row-between u-padding-30 u-border-bottom">
								<text>{{item.label}}</text>
								<u-icon v-if="isChooseP&&province===index"  size="34" color="rgb(118, 92, 254)" name="checkbox-mark"></u-icon>
							</view>
						</scroll-view>
					</view>
				</view>
				<view class="area-item">
					<view class="u-padding-10 u-bg-gray" style="height: 100%;">
						<scroll-view :scroll-y="true" style="height: 100%">
							<template  v-if="isChooseP">
								<view v-for="(item,index) in citys" :key="index"
								 @click="cityChange(index)" class="u-flex u-row-between u-padding-30 u-border-bottom">
									<text>{{item.label}}</text>
									<u-icon v-if="isChooseC&&city===index"  size="34" color="rgb(118, 92, 254)" name="checkbox-mark"></u-icon>
								</view>
							</template>
						</scroll-view>
					</view>
         
				</view>

				<view class="area-item">
					<view class="u-padding-10 u-bg-gray" style="height: 100%;">
						<scroll-view :scroll-y="true" style="height: 100%">
							<template  v-if="isChooseC">
								<view v-for="(item,index) in areas" :key="index"
								 @click="areaChange(index)" class="u-flex u-row-between u-padding-30 u-border-bottom">
									<text>{{item.label}}</text>
									<u-icon v-if="isChooseA&&area===index"  size="34" color="rgb(118, 92, 254)" name="checkbox-mark"></u-icon>
								</view>
							</template>
						</scroll-view>
					</view>
				</view>
			</view>
		</view>
    <view class="bottomConfirm" @click="close" v-if="comfirm">确认</view>
	</u-popup>
</template>

<script>
	import {getCity} from '@/api/data.js'
	/**
	 * city-select 省市区级联选择器
	 * @property {String Number} z-index 弹出时的z-index值（默认1075）
	 * @property {Boolean} mask-close-able 是否允许通过点击遮罩关闭Picker（默认true）
	 * @property {String} default-region 默认选中的地区，中文形式
	 * @property {String} default-code 默认选中的地区，编号形式
	 */
	export default {
		name: 'u-city-select',
		props: {
			// 通过双向绑定控制组件的弹出与收起
			value: {
				type: Boolean,
				default: false
			},
			// 默认显示的地区，可传类似["河北省", "秦皇岛市", "北戴河区"]
			defaultRegion: {
				type: Array,
				default () {
					return [];
				}
			},
      comfirm: { // 是否显示确认按钮
        type:Boolean,
				default:false
      },
			// 默认显示地区的编码，defaultRegion和areaCode同时存在，areaCode优先，可传类似["13", "1303", "130304"]
			areaCode: {
				type: Array,
				default () {
					return [];
				}
			},
			// 是否允许通过点击遮罩关闭Picker
			maskCloseAble: {
				type: Boolean,
				default: true
			},
			// 弹出的z-index值
			zIndex: {
				type: [String, Number],
				default: 0
			},
			cityList:{
				type: Array,
				default () {
					return [];
				}
			}
		},
		data() {
			return {
				cityValue: "",
				isChooseP: false, //是否已经选择了省
				province: 0, //省级下标
				provinces: [],
				isChooseC: false, //是否已经选择了市
				city: 0, //市级下标
				citys:[],
				isChooseA: false, //是否已经选择了区
				area: 0, //区级下标
				areas:[],
				tabsIndex: 0,
				result:{
					province:{},
					city:{},
					area:{}
				},
        tabsList:[{
					name: "请选择"
				}]
			}
		},
		async created() {
			await this.getCity()
			setTimeout(()=>{
				this.init();
			},200)
		},
		computed: {
			isChange() {
				return this.tabsIndex > 1;
			},
			genTabsList() {
				let tabsList = [{
					name: "请选择"
				}];
				if (this.isChooseP) {
					tabsList[0]['name'] = this.provinces[this.province]['label'];
					tabsList[1] = {
						name: "请选择"
					};
				}
				if (this.isChooseC) {
					tabsList[1]['name'] = this.citys[this.city]['label'];
					tabsList[2] = {
						name: "请选择"
					};
				}
				if (this.isChooseA) {
					tabsList[2]['name'] = this.areas[this.area]['label'];
				}
				return tabsList;
			},
			uZIndex() {
				// 如果用户有传递z-index值，优先使用
				return this.zIndex ? this.zIndex : this.$u.zIndex.popup;
			}
		},
		methods: {
			getCity(parentId=-1){
				return getCity({parentId}).then(res=>{
					const mapStr = ['provinces','citys','areas'][this.tabsIndex];
					this[mapStr] = res.content
				})
			},
			async init() {
				if (this.areaCode.length == 3) {
					this.setProvince("", this.areaCode[0]);
					this.setCity("", this.areaCode[1]);
					this.setArea("", this.areaCode[2]);
				} else if (this.defaultRegion&&this.defaultRegion.length>0) {
					await this.setProvince(this.defaultRegion[0], "");
				};
			},
			async setProvince(label = "", value = "") {
				const index = this.provinces.findIndex(v=>value ? v.value == value : v.label == label)
				index>0&&this.provinceChange(index,'default');
			},
			async setCity(label = "", value = "") {
				const index = this.citys.findIndex(v=>value ? v.value == value : v.label == label)
				index>0&&this.cityChange(index,'default');
			},
			async setArea(label = "", value = "") {
				const index = this.areas.findIndex(v=>value ? v.value == value : v.label == label)
				index>0&&this.areaChange(index,'default');
			},
			close() {
				this.$emit('input', false);
				this.$emit('city-select', this.result);
			},
			tabsChange(index) {
				this.tabsIndex = index;
        console.log(index,'哈哈哈哈');
			},
			async provinceChange(index,type) {
				this.isChooseP = true;
				this.isChooseC = false;
				this.isChooseA = false;
				this.province = index;
				this.tabsIndex = 1;
				this.result = {
					province:{},
					city:{},
					area:{}
				}
				const parentObj = this.provinces[index]
				await this.getCity(parentObj.id) || {}
				this.$set(this.result,'province',parentObj)
				this.$emit('city-change', this.result);
				if(type==='default'){
					this.setCity(this.defaultRegion[1], "");
				}
			},
			async cityChange(index,type) {
				try{
					this.isChooseC = true;
					this.isChooseA = false;
					this.city = index;
					this.tabsIndex = 2;
					const parentObj = this.citys[index] || {}
					await this.getCity(parentObj.id)
					this.$set(this.result,'city',parentObj)
					//this.$set(this.result,'area',{})
					this.$emit('city-change', this.result);
					if(type==='default'){
						this.setArea(this.defaultRegion[2], "");
					}else{
						this.$set(this.result,'area',{})
					}
				}catch(e){
					console.log("e: " + JSON.stringify(e));
					//TODO handle the exception
				}
			},
			areaChange(index,type) {
				this.isChooseA = true;
				this.area = index;
				this.tabsIndex = 2;
				const parentObj = this.areas[index] || {}
				this.$set(this.result,'area',parentObj)
				this.$emit('city-change', this.result);
				this.$emit('city-select', this.result);
				if(type!=='default') this.close();
				console.log(this.tabsIndex)
			}
		}

	}
</script>
<style lang="scss">
	.area-box {
		width: 100%;
		overflow: hidden;
		height: 800rpx;

		>view {
			width: 150%;
			transition: transform 0.3s ease-in-out 0s;
			transform: translateX(0);

			&.change {
				transform: translateX(-33.3333333%);
			}
		}

		.area-item {
			width: 33.3333333%;
			height: 800rpx;
		}
	}

  .send {
  position: absolute;
  top: 22rpx;
  right: 92rpx;
  width: 120rpx;
  height: 50rpx;
  margin-left: 30rpx;
  background-color: #765CFE;
  border-radius: 37rpx;
  color: #fff;
  font-size: 24rpx;
  text-align: center;
  line-height: 50rpx;
}

.bottomConfirm {
  // transform: translateX(50vw);
  width: 240rpx;
  height:80rpx;
  margin-left: 30rpx;
  background-color: #765CFE;
  // margin-top: 50rpx;
  // margin-right: 50rpx;
  margin: 20rpx auto;
  border-radius: 50rpx;
  color: #fff;
  font-size: 30rpx;
  text-align: center;
  line-height: 80rpx;
}
</style>
